package com.z.security.filter;

import com.alibaba.fastjson.JSON;
import com.z.entity.security.Admin;
import com.z.result.ResultWrapper;
import com.z.service.UsersService;
import com.z.utils.token.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.util.WebUtils;


import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class JWTCheckFilter extends OncePerRequestFilter {

    public JWTCheckFilter() {
        super();
    }

    @Autowired
    UsersService usersService;

    @Override
    protected boolean shouldNotFilter(HttpServletRequest request) throws ServletException {

        String requestUrl = request.getRequestURI();

        System.out.println(requestUrl);

        if (requestUrl.contains("swagger") || requestUrl.contains("v3") || requestUrl.contains("webjars") ||  requestUrl.contains("easy-captcha")) {
            return true;
        }

        return false;

    }

    @Override
    protected void doFilterInternal(HttpServletRequest Request, HttpServletResponse Response, FilterChain filterChain) throws ServletException, IOException {

        System.out.println("静茹过滤器");

        String token = Request.getHeader("token");

        if (token == null) {

           return;
        }

        String subject = JwtUtil.parseToken(token);

        Admin adminByLoginAcct = usersService.getAdminByLoginAcct(subject);

        if(adminByLoginAcct != null){

            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(adminByLoginAcct.getLoginAcct(),adminByLoginAcct.getUserPswd());
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        }

        filterChain.doFilter(Request,Response);



    }
}
